/**
 * API客户端 - 负责与后端API通信
 * 提供统一的数据获取接口
 */

class APIClient {
    constructor() {
        this.baseURL = 'http://127.0.0.1:8000/api/v1';
        this.timeout = 10000;
        this.cache = new Map();
        this.cacheTimeout = 5 * 60 * 1000; // 5分钟缓存
        
        // 配置axios默认设置
        axios.defaults.timeout = this.timeout;
        axios.defaults.headers.common['Content-Type'] = 'application/json';
        
        // 请求拦截器
        axios.interceptors.request.use(
            config => {
                this.showLoading();
                return config;
            },
            error => {
                this.hideLoading();
                return Promise.reject(error);
            }
        );
        
        // 响应拦截器
        axios.interceptors.response.use(
            response => {
                this.hideLoading();
                this.updateConnectionStatus(true);
                return response;
            },
            error => {
                this.hideLoading();
                this.updateConnectionStatus(false);
                this.handleError(error);
                return Promise.reject(error);
            }
        );
    }
    
    /**
     * 显示加载指示器
     */
    showLoading() {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) {
            overlay.classList.add('show');
        }
    }
    
    /**
     * 隐藏加载指示器
     */
    hideLoading() {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) {
            overlay.classList.remove('show');
        }
    }
    
    /**
     * 更新连接状态
     */
    updateConnectionStatus(isConnected) {
        const status = document.getElementById('connectionStatus');
        if (status) {
            if (isConnected) {
                status.innerHTML = '<i class="fas fa-circle"></i> 连接正常';
                status.style.background = 'rgba(76, 175, 80, 0.2)';
                status.style.borderColor = 'rgba(76, 175, 80, 0.3)';
            } else {
                status.innerHTML = '<i class="fas fa-exclamation-circle"></i> 连接异常';
                status.style.background = 'rgba(244, 67, 54, 0.2)';
                status.style.borderColor = 'rgba(244, 67, 54, 0.3)';
            }
        }
    }
    
    /**
     * 错误处理
     */
    handleError(error) {
        console.error('API请求错误:', error);
        
        let message = '请求失败';
        if (error.response) {
            message = `服务器错误: ${error.response.status}`;
        } else if (error.request) {
            message = '网络连接失败';
        } else {
            message = error.message;
        }
        
        this.showNotification(message, 'error');
    }
    
    /**
     * 显示通知
     */
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <i class="fas fa-${type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
            <span>${message}</span>
            <button onclick="this.parentElement.remove()">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 100px;
            right: 20px;
            background: ${type === 'error' ? '#f44336' : '#2196f3'};
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            z-index: 10001;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            max-width: 400px;
            animation: slideInRight 0.3s ease-out;
        `;
        
        document.body.appendChild(notification);
        
        // 自动移除
        setTimeout(() => {
            if (notification.parentElement) {
                notification.remove();
            }
        }, 5000);
    }
    
    /**
     * 缓存管理
     */
    getCachedData(key) {
        const cached = this.cache.get(key);
        if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
            return cached.data;
        }
        return null;
    }
    
    setCachedData(key, data) {
        this.cache.set(key, {
            data: data,
            timestamp: Date.now()
        });
    }
    
    /**
     * 通用GET请求
     */
    async get(endpoint, useCache = true) {
        const cacheKey = `GET:${endpoint}`;
        
        if (useCache) {
            const cached = this.getCachedData(cacheKey);
            if (cached) {
                return cached;
            }
        }
        
        try {
            const response = await axios.get(`${this.baseURL}${endpoint}`);
            const data = response.data;
            
            if (useCache) {
                this.setCachedData(cacheKey, data);
            }
            
            return data;
        } catch (error) {
            throw error;
        }
    }
    
    /**
     * 通用POST请求
     */
    async post(endpoint, data) {
        try {
            const response = await axios.post(`${this.baseURL}${endpoint}`, data);
            return response.data;
        } catch (error) {
            throw error;
        }
    }
    
    // ==================== 仪表板相关API ====================
    
    /**
     * 获取仪表板KPI数据
     */
    async getDashboardKPIs() {
        return await this.get('/analytics/dashboard');
    }
    
    /**
     * 获取业务活动数据
     */
    async getBusinessActivities() {
        return await this.get('/business-activities');
    }
    
    // ==================== 库存管理相关API ====================
    
    /**
     * 获取库存数据
     */
    async getInventoryData(filters = {}) {
        const params = new URLSearchParams(filters).toString();
        const endpoint = `/inventory${params ? '?' + params : ''}`;
        return await this.get(endpoint);
    }
    
    /**
     * 获取库存统计
     */
    async getInventoryStats() {
        return await this.get('/inventory/stats');
    }
    
    /**
     * 获取仓库列表
     */
    async getWarehouses() {
        return await this.get('/inventory/warehouses');
    }
    
    /**
     * 获取产品类别
     */
    async getProductCategories() {
        return await this.get('/inventory/categories');
    }
    
    // ==================== 订单管理相关API ====================
    
    /**
     * 获取订单数据
     */
    async getOrdersData(filters = {}) {
        const params = new URLSearchParams(filters).toString();
        const endpoint = `/orders${params ? '?' + params : ''}`;
        return await this.get(endpoint);
    }
    
    /**
     * 获取订单统计
     */
    async getOrderStats() {
        return await this.get('/orders/stats');
    }
    
    /**
     * 获取订单详情
     */
    async getOrderDetail(orderId) {
        return await this.get(`/orders/${orderId}`);
    }
    
    // ==================== 智能分析相关API ====================
    
    /**
     * 获取需求预测数据
     */
    async getDemandForecast(params = {}) {
        const queryParams = new URLSearchParams(params).toString();
        const endpoint = `/analytics/demand-forecast${queryParams ? '?' + queryParams : ''}`;
        return await this.get(endpoint, false); // 预测数据不使用缓存
    }
    
    /**
     * 获取库存优化建议
     */
    async getInventoryOptimization() {
        return await this.get('/analytics/inventory-optimization', false);
    }
    
    /**
     * 获取供应商绩效分析
     */
    async getSupplierPerformance() {
        return await this.get('/analytics/supplier-performance');
    }
    
    /**
     * 获取市场趋势分析
     */
    async getMarketTrends() {
        return await this.get('/analytics/market-trends');
    }
    
    /**
     * 获取智能分析仪表板
     */
    async getIntelligentDashboard() {
        return await this.get('/analytics/intelligent-dashboard');
    }
    
    // ==================== 质量管理相关API ====================
    
    /**
     * 获取质量仪表板数据
     */
    async getQualityDashboard() {
        return await this.get('/quality/dashboard');
    }
    
    /**
     * 获取质量检验数据
     */
    async getQualityInspections(filters = {}) {
        const params = new URLSearchParams(filters).toString();
        const endpoint = `/quality/inspections${params ? '?' + params : ''}`;
        return await this.get(endpoint);
    }
    
    /**
     * 获取质量标准
     */
    async getQualityStandards() {
        return await this.get('/quality/standards');
    }
    
    /**
     * 获取缺陷数据
     */
    async getDefects(filters = {}) {
        const params = new URLSearchParams(filters).toString();
        const endpoint = `/quality/defects${params ? '?' + params : ''}`;
        return await this.get(endpoint);
    }
    
    /**
     * 获取CAPA数据
     */
    async getCAPAs(filters = {}) {
        const params = new URLSearchParams(filters).toString();
        const endpoint = `/quality/capas${params ? '?' + params : ''}`;
        return await this.get(endpoint);
    }
    
    // ==================== 图表数据相关API ====================
    
    /**
     * 获取库存状态图表数据
     */
    async getInventoryChartData(period = 30) {
        return await this.get(`/charts/inventory-status?period=${period}`);
    }
    
    /**
     * 获取订单趋势图表数据
     */
    async getOrderTrendChartData(period = 30) {
        return await this.get(`/charts/order-trends?period=${period}`);
    }
    
    /**
     * 获取采购图表数据
     */
    async getProcurementChartData(period = 30) {
        return await this.get(`/charts/procurement-performance?period=${period}`);
    }
    
    /**
     * 获取生产图表数据
     */
    async getProductionChartData(period = 30) {
        return await this.get(`/charts/production-efficiency?period=${period}`);
    }
    
    /**
     * 获取配送图表数据
     */
    async getDeliveryChartData(period = 30) {
        return await this.get(`/charts/delivery-performance?period=${period}`);
    }
    
    /**
     * 获取质量图表数据
     */
    async getQualityChartData(period = 30) {
        return await this.get(`/charts/quality-metrics?period=${period}`);
    }
    
    // ==================== 工具方法 ====================
    
    /**
     * 清除缓存
     */
    clearCache() {
        this.cache.clear();
        this.showNotification('缓存已清除', 'info');
    }
    
    /**
     * 刷新所有数据
     */
    async refreshAllData() {
        this.clearCache();
        
        // 重新加载当前模块数据
        const activeModule = document.querySelector('.nav-link.active')?.dataset.module;
        if (activeModule && window.app) {
            await window.app.loadModuleData(activeModule);
        }
        
        this.showNotification('数据已刷新', 'info');
    }
    
    /**
     * 测试API连接
     */
    async testConnection() {
        try {
            await this.get('/health', false);
            this.showNotification('API连接正常', 'info');
            return true;
        } catch (error) {
            this.showNotification('API连接失败', 'error');
            return false;
        }
    }
    
    /**
     * 导出数据
     */
    async exportData(endpoint, filename) {
        try {
            const response = await axios.get(`${this.baseURL}${endpoint}`, {
                responseType: 'blob'
            });
            
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            link.remove();
            window.URL.revokeObjectURL(url);
            
            this.showNotification('数据导出成功', 'info');
        } catch (error) {
            this.showNotification('数据导出失败', 'error');
        }
    }
}

// 创建全局API客户端实例
window.apiClient = new APIClient();

// 添加通知样式
const notificationStyles = document.createElement('style');
notificationStyles.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    .notification button {
        background: none;
        border: none;
        color: white;
        cursor: pointer;
        padding: 0.25rem;
        border-radius: 4px;
        margin-left: auto;
    }
    
    .notification button:hover {
        background: rgba(255,255,255,0.2);
    }
`;
document.head.appendChild(notificationStyles);



// 全局导出数据函数
window.exportData = () => {
    const activeModule = document.querySelector('.nav-link.active')?.dataset.module;
    if (activeModule) {
        const filename = `${activeModule}_data_${new Date().toISOString().split('T')[0]}.csv`;
        window.apiClient.exportData(`/${activeModule}/export`, filename);
    }
};